var origins={};
var movers=[];

function init() {
//  alert('tuio init');
	tuio.start();
}

tuio.cursor_add(function(data) {
	var px = data.x * window.innerWidth;
	var py = data.y * window.innerHeight;

  console.log('finger added: '+data.x+', '+data.y);
  origins[data.sid]=[data.x, data.y];              
});

tuio.cursor_update(function(data) {
	var px = data.x * window.innerWidth;
	var py = data.y * window.innerHeight;

  console.log('finger moved: '+data.sid+':'+data.fid+' / '+data.x+', '+data.y);
  if(movers.indexOf(data.sid)==-1)
  {
    movers.push(data.sid);
  }
  console.log('new mover: '+data.sid);
});

tuio.cursor_remove(function(data) {
	var px = data.x * window.innerWidth;
	var py = data.y * window.innerHeight;

  console.log('finger removed: '+data.sid+':'+data.fid+' / '+data.x+', '+data.y);
  var mindex=movers.indexOf(data.sid);
  if(mindex!=-1)
  {
    mover=movers[mindex];
    console.log('lost mover: '+mover);
    movers.splice(movers.indexOf(data.sid), 1);

    if(movers.length==0) // One-finger drag
    {
      swipe(mover, data);
    }
    else if(movers.length==1) // Two-finger drag
    {
      pinch(movers.pop(), data.sid, data);
    }
    // else 3+ finger drag not supported
  }
  
  origins[data.sid]=null;
});

function swipe(mover, data)
{
  console.log('pinch: '+origins[mover]+' / '+data.x+', '+data.y);
  var vector=[data.x-origins[mover][0], data.y-origins[mover][1]];
  console.log('vector: '+vector);
  pan(vector);
}

function pinch(a, b, data)
{
  oa=origins[a];
  ob=origins[b];
  d1=distance(oa, ob);
  d2=distance(oa, [data.x, data.y]);

  console.log('pinch: '+d1+', '+d2);
  zoom(d2-d1);
}

function distance(a, b)
{
  return Math.sqrt(Math.pow(b[0]-a[0], 2)+Math.pow(b[1]-a[1], 2));
}

function pan(vector)
{
  //map.panBy(new GSize(vector[0]*1000, vector[1]*1000));
  dx=vector[0]*10;
  dy=vector[1]*10;
    
  if(dx>1)
  {
    dx=1;
  }
  else if(dx<-1)
  {
    dx=-1;
  }
  else
  {
    dx=0;
  }
    
  if(dy>1)
  {
    dy=1;
  }
  else if(dy<-1)
  {
    dy=-1;
  }
  else
  {
    dy=0;
  }
        
  console.log('panning '+dx+', '+dy);
  map.panDirection(dx, dy);
}

function zoom(scale)
{
  console.log('zoom: '+scale);
  if(scale>0)
  {
    map.zoomOut(map.getCenter(), true);
  }
  else
  {
    map.zoomIn(map.getCenter(), true);
  }
}

$(document).ready(init);